package com.koron.util;

import com.koron.common.web.service.SynchronizationOrgService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.FieldUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @author admin
 * @deprecated: 树结构工具类
 * @date 2021.07.28
 */
public class TreeUtils {
    /** 
     * 把列表转换为树结构
     *
     * @param originalList      原始list数据     
     * @param idFieldName       作为唯一标示的字段名称
     * @param pidFieldName      父节点标识字段名
     * @param childrenFieldName 子节点（列表）标识字段名
     * @return 树结构列表
     */
    public static <T> List<T> list2TreeList(List<T> originalList, String idFieldName, String pidFieldName,
                                            String childrenFieldName) {
        // 获取根节点，即找出父节点为0的对象
        List<T> rootNodeList = new ArrayList<>();
        for (T t : originalList) {
            String parentId = null;
            try {
                parentId = BeanUtils.getProperty(t, pidFieldName);
            } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                e.printStackTrace();
            }
            if (StringUtils.isEmpty(parentId)){
                parentId = SynchronizationOrgService.getRoot();
            }
            if (SynchronizationOrgService.getRoot().equals(parentId)) {
                rootNodeList.add(0, t);
            }
        }

        // 将根节点从原始list移除，减少下次处理数据
        originalList.removeAll(rootNodeList);

        // 递归封装树
        try {
            packTree(rootNodeList, originalList, idFieldName, pidFieldName, childrenFieldName);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return rootNodeList;
    }

    /**
     * 封装树（向下递归）
     *
     * @param parentNodeList    要封装为树的父节点对象集合
     * @param originalList      原始list数据
     * @param keyName           作为唯一标示的字段名称
     * @param pidFieldName      父节点标识字段名
     * @param childrenFieldName 子节点（列表）标识字段名
     */
    private static <T> void packTree(List<T> parentNodeList, List<T> originalList, String keyName,
                                     String pidFieldName, String childrenFieldName) throws Exception {
        for (T parentNode : parentNodeList) {
            // 找到当前父节点的子节点列表
            List<T> children = packChildren(parentNode, originalList, keyName, pidFieldName, childrenFieldName);
            if (children.isEmpty()) {
                continue;
            }

            // 将当前父节点的子节点从原始list移除，减少下次处理数据
            originalList.removeAll(children);

            // 开始下次递归
            packTree(children, originalList, keyName, pidFieldName, childrenFieldName);
        }
    }

    /**
     * 封装子对象
     *
     * @param parentNode        父节点对象
     * @param originalList      原始list数据
     * @param keyName           作为唯一标示的字段名称
     * @param pidFieldName      父节点标识字段名
     * @param childrenFieldName 子节点（列表）标识字段名
     */
    private static <T> List<T> packChildren(T parentNode, List<T> originalList, String keyName, String pidFieldName,
                                            String childrenFieldName) throws Exception {
        // 找到当前父节点下的子节点列表
        List<T> childNodeList = new ArrayList<>();
        String parentId = BeanUtils.getProperty(parentNode, keyName);
        for (T t : originalList) {
            String childNodeParentId = BeanUtils.getProperty(t, pidFieldName);
            if (parentId.equals(childNodeParentId)) {
                childNodeList.add(t);
            }
        }

        // 将当前父节点下的子节点列表写入到当前父节点下（给子节点列表字段赋值）
        if (!childNodeList.isEmpty()) {
            FieldUtils.writeDeclaredField(parentNode, childrenFieldName, childNodeList, true);
        }

        return childNodeList;
    }

    /**
     * 根据父id查询子列表
     * @param list
     * @param fieldName
     * @param childrenFieldName
     * @param pid
     * @param <T>
     * @return
     */
    public static <T> List<T> searchByParentCode(List<T> list,String fieldName,String childrenFieldName, String pid){
        if (StringUtils.isEmpty(pid)) {
            return list;
        }
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        for (T item : list) {
            String currId = null;
            try {
                currId = BeanUtils.getProperty(item, fieldName);
            } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                e.printStackTrace();
            }
            List<T> children = new ArrayList<>();
            try {
                String getMethodName = "get" + childrenFieldName.substring(0, 1).toUpperCase() + childrenFieldName.substring(1);
                Class<?> tCls = item.getClass();// 泛型为Object以及所有Object的子类
                Method getMethod = tCls.getMethod(getMethodName);// 通过方法名得到对应的方法
                children = (List<T>)getMethod.invoke(item);
            } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException e) {
                e.printStackTrace();
            }
            if (pid.equals(currId)){
                return children;
            } else {
                return searchByParentCode(children,fieldName,childrenFieldName,pid);
            }
        }
        return new ArrayList<>();
    }

    /**
     * 根据id查询节点
     * @param list
     * @param fieldName
     * @param childrenFieldName
     * @param id
     * @param <T>
     * @return
     */
    public static <T> T searchNodeByCode(List<T> list,String fieldName,String childrenFieldName, String id){
        if (StringUtils.isEmpty(id)) {
            return null;
        }
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        for (T item : list) {
            String currId = null;
            try {
                currId = BeanUtils.getProperty(item, fieldName);
            } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                e.printStackTrace();
            }
            List<T> children = new ArrayList<>();
            try {
                String getMethodName = "get" + childrenFieldName.substring(0, 1).toUpperCase() + childrenFieldName.substring(1);
                Class<?> tCls = item.getClass();// 泛型为Object以及所有Object的子类
                Method getMethod = tCls.getMethod(getMethodName);// 通过方法名得到对应的方法
                children = (List<T>)getMethod.invoke(item);
            } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException e) {
                e.printStackTrace();
            }
            if (id.equals(currId)){
                return item;
            } else {
                return searchNodeByCode(children,fieldName,childrenFieldName,id);
            }
        }
        return null;
    }
}